package com.guo.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guo.config.AjaxResult;
import com.guo.entity.Movie;
import com.guo.query.MovieQuery;
import com.guo.entity.service.IMovieService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Api(tags = "电影接口",description = "电影接口详细描述")
@RequestMapping("/movie")
public class MovieController {

    @Autowired
    private IMovieService service;

    @GetMapping("/findAll")
    @ApiOperation(value = "查找所有电影")
    public AjaxResult findAll(){
        try {
            List<Movie> all = service.getAll();
            return AjaxResult.me(all);
        } catch (Exception e) {
            return AjaxResult.me("查询失败");
        }
    }

    @GetMapping("/find/{id}")
    @ApiOperation(value = "根据id查找电影")
    public AjaxResult findById(@PathVariable("id") Integer id){
        try {
            Movie movie = service.getById(id);
            return AjaxResult.me(movie);
        } catch (Exception e) {
            return AjaxResult.me("查询失败");
        }
    }

    @PutMapping("/add")
    @ApiOperation(value = "添加或修改电影",notes = "有id表示修改,没有则表示添加")
    public AjaxResult save(@RequestBody Movie movie){
        AjaxResult r = AjaxResult.me();
        int i;
        try {
            if (movie.getId()!=null && movie.getId()!=0){ //更新
                i = service.updateById(movie);
            }else { //添加
                i = service.addById(movie);
            }
            r.setSuccess(i > 0);  //大于0则true，否则false
        } catch (Exception e) {
            r.setSuccess(false);
            r.setMsg("添加修改失败");
        }
        return r;
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除电影",notes = "")
    public AjaxResult remove(@PathVariable("id") Integer id){
        AjaxResult r = AjaxResult.me();
        try {
            int i = service.removeById(id);
            r.setSuccess(i > 0);
        } catch (Exception e) {
            r.setSuccess(false);
            r.setMsg("删除失败");
        }
        return r;
    }

    @PostMapping
    @ApiOperation(value = "高级分页查询",notes = "")
    public AjaxResult getPages(@RequestBody MovieQuery query){
        PageHelper.startPage(query.getCurrentPage(),query.getPageSize());
        try {
            PageInfo<Movie> pageInfo = service.pageAll(query);
            return AjaxResult.me(pageInfo);
        } catch (Exception e) {
            return AjaxResult.me("查询失败");
        }
    }


}
